Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
280 changes: 207 additions & 73 deletions ProcessMaker/Http/Controllers/Api/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use ProcessMaker\Events\UserCreated;
use ProcessMaker\Events\UserDeleted;
use ProcessMaker\Events\UserGroupMembershipUpdated;
Expand Down Expand Up @@ -63,6 +64,7 @@
'timezone',
'datetime_format',
'status',
'delegation_user_id',
'avatar',
'preferences_2fa',
'connected_accounts',
Expand All @@ -79,6 +81,17 @@
'disableRecommendations',
];

/**
* Statuses a personal-profile user may set on their own account.
*
* @var array<string>
*/
private const SELF_SERVICE_STATUSES = [
'ACTIVE',
'INACTIVE',
'OUT_OF_OFFICE',
];

/**
* Display a listing of the resource.
*
Expand Down Expand Up @@ -506,7 +519,7 @@
* @OA\Response(response=422, ref="#/components/responses/422"),
* )
*/
public function update(User $user, Request $request)

Check warning on line 522 in ProcessMaker/Http/Controllers/Api/UserController.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

This method has 5 returns, which is more than the 3 allowed.

[S1142] Functions should not contain too many return statements See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9098&issues=2a383d38-6ba8-4bc9-9210-08221cc8ea07&open=2a383d38-6ba8-4bc9-9210-08221cc8ea07
{
$authenticatedUser = Auth::user();
if (!$authenticatedUser->can('edit', $user)) {
Expand All @@ -517,20 +530,13 @@
$isSelfServiceUpdate = $this->authorizeSelfServiceUpdate($authenticatedUser, $user, $fields);
$rules = User::rules($user);
if ($isSelfServiceUpdate) {
$rules['meta'] = ['sometimes', 'array'];
$rules['meta.disableRecommendations'] = ['sometimes', 'boolean'];
[$fields, $rules] = $this->prepareSelfServiceUpdate($user, $request, $fields, $rules);
}
$request->validate($rules);
if ($isSelfServiceUpdate) {
$fields = $this->normalizeSelfServiceMeta($user, $fields);
}
if (isset($fields['password'])) {
$fields['password'] = Hash::make($fields['password']);
$fields['password_changed_at'] = Carbon::now()->toDateTimeString();

// Remove login error message related to password expired if exists
session()->forget('login-error');
}
$fields = $this->hashPasswordFields($fields);
$original = $user->getOriginal();
$isLdapUser = isset($user->meta?->authenticationType)
&& $user->meta->authenticationType === 'ldap';
Expand All @@ -541,45 +547,9 @@
return $response;
}
}
if ($fields['email'] !== $original['email']) {
$ssoUser = $isLdapUser;
if (class_exists(SsoUser::class)) {
// Check if the user is an SSO user (including SAML)
$ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists();
}
if ($ssoUser) {
return response([
'message' => __(
"The email can't be edited. This action is only available for SSO-synced users."
),
'errors' => [
'email' => [
__(
"The email can't be edited. This action is only available for SSO-synced users."
),
],
],
], 422);
}
if (!isset($fields['valpassword'])) {
return response([
'message' => __(
'A valid authentication is required for for update the email.'
),
'errors' => [
'email' => [
__(
'The password is required.'
),
],
],
], 422);
} else {
$response = $this->validateBeforeChange(Auth::user(), $fields['valpassword']);
if ($response) {
return $response;
}
}
$emailChangeResponse = $this->validateEmailChange($user, $fields, $original, $isLdapUser);
if ($emailChangeResponse) {
return $emailChangeResponse;
}
if (Auth::user()->is_administrator && $request->has('is_administrator')) {
// user must be an admin to make another user an admin
Expand All @@ -590,37 +560,18 @@
$user->meta = null;
}

try {
$user->saveOrFail();
} catch (\Exception $e) {
$slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException';

if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) {
return response([
'message' => $e->getMessage(),
], 422);
}

throw $e;
$saveResponse = $this->saveUserOrFail($user);
if ($saveResponse) {
return $saveResponse;
}

$changes = $user->getChanges();

//Call new Event to store User Changes into LOG
UserUpdated::dispatch($user, $changes, $original);
try {
if ($request->has('avatar')) {
$this->uploadAvatar($user, $request);
}
} catch (\Exception $e) {
return response([
'message' => 'Error uploading avatar',
'errors' => [
'avatar' => [
$e->getMessage(),
],
],
], 422);
$avatarResponse = $this->maybeUploadAvatar($user, $request);
if ($avatarResponse) {
return $avatarResponse;
}

RecommendationEngine::handleUserSettingChanges($user, $original);
Expand Down Expand Up @@ -660,6 +611,189 @@
return true;
}

/**
* Clear stale delegation, sync request JSON, and tighten self-service rules.
*
* @return array{0: array, 1: array}
*/
private function prepareSelfServiceUpdate(User $user, Request $request, array $fields, array $rules): array
{
$fields = $this->forgetUnassignableDelegation($fields);
if (array_key_exists('delegation_user_id', $fields)) {
$request->json()->set('delegation_user_id', $fields['delegation_user_id']);
}
$rules['meta'] = ['sometimes', 'array'];
$rules['meta.disableRecommendations'] = ['sometimes', 'boolean'];
$rules['status'] = ['required', Rule::in($this->selfServiceStatuses($user))];
$rules['delegation_user_id'] = [

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Agentic Security Review

Severity: MEDIUM

Description: A user with only edit-personal-profile can PUT /api/1.0/users/{self} and store status OUT_OF_OFFICE plus delegation_user_id set to any other active, non-system user. Process-variable assignment then puts that delegate into the assignee pool with no check that they are on the task's user or group list. The resulting process_request_tokens.user_id is enough for ProcessRequestTokenPolicy to allow view and complete, and for ForUserScope to show the parent request.

Impact: The previous self-service denylist kept delegation_user_id with manager_id, so only an edit-users administrator could name a backup. This change lets an ordinary profile user redirect future process-variable work — including request data and task completion — to an account the process never assigned. That is a cross-user task and request-data boundary, not a personal display preference. Fixed user, group, and user_by_id assignment do not perform this substitution, and delegateTask only writes an assignee when an external assignment process exists.

Remediation: Do not accept an unconstrained delegation_user_id on the personal-profile allowlist. Keep the column admin-managed, or before saving it require a relationship that is allowed to receive this user's work (same task assignment list, shared group, or an explicit delegate grant). Apply that same check in getNextUserFromProcessVariable and getNextUserFromProcessVariableRaw before copying the id into process_request_tokens.user_id.

'nullable',
'integer',
Rule::exists('users', 'id')->where(function ($query) {
$query->where('is_system', false)
->whereNull('deleted_at')
->where('status', 'ACTIVE');
}),
Rule::notIn([(string) $user->id]),
];

return [$fields, $rules];
}

/**
* Hash an incoming password and clear the expired-password login error.
*/
private function hashPasswordFields(array $fields): array
{
if (!isset($fields['password'])) {
return $fields;
}

$fields['password'] = Hash::make($fields['password']);
$fields['password_changed_at'] = Carbon::now()->toDateTimeString();

// Remove login error message related to password expired if exists
session()->forget('login-error');

return $fields;
}

/**
* Block email changes for SSO users, and require password confirmation otherwise.
*
* @return \Illuminate\Http\Response|false
*/
private function validateEmailChange(User $user, array $fields, array $original, bool $isLdapUser)

Check warning on line 665 in ProcessMaker/Http/Controllers/Api/UserController.php

View check run for this annotation

Decisions SonarQube / SonarQube Code Analysis

This method has 4 returns, which is more than the 3 allowed.

[S1142] Functions should not contain too many return statements See more on https://builds.decisions.com:9000/project/issues?id=ProcessMaker_processmaker_AYkzkfKexYvY_isvKt07&pullRequest=9098&issues=5fd5f275-8906-452d-835a-025ce57a047c&open=5fd5f275-8906-452d-835a-025ce57a047c
{
if ($fields['email'] === $original['email']) {
return false;
}

$ssoUser = $isLdapUser;
if (class_exists(SsoUser::class)) {
// Check if the user is an SSO user (including SAML)
$ssoUser = $ssoUser || SsoUser::where('user_id', $user->id)->exists();
}
if ($ssoUser) {
return response([
'message' => __(
"The email can't be edited. This action is only available for SSO-synced users."
),
'errors' => [
'email' => [
__(
"The email can't be edited. This action is only available for SSO-synced users."
),
],
],
], 422);
}
if (!isset($fields['valpassword'])) {
return response([
'message' => __(
'A valid authentication is required for for update the email.'
),
'errors' => [
'email' => [
__(
'The password is required.'
),
],
],
], 422);
}

return $this->validateBeforeChange(Auth::user(), $fields['valpassword']);
}

/**
* Persist the user, mapping Slack config failures to a 422 response.
*
* @return \Illuminate\Http\Response|null
*/
private function saveUserOrFail(User $user)
{
try {
$user->saveOrFail();
} catch (\Exception $e) {
$slackExceptionClass = 'ProcessMaker\Packages\Connectors\Slack\Exceptions\SlackConfigurationException';

if (class_exists($slackExceptionClass) && $e instanceof $slackExceptionClass) {
return response([
'message' => $e->getMessage(),
], 422);
}

throw $e;
}

return null;
}

/**
* Upload an avatar when requested, mapping failures to a 422 response.
*
* @return \Illuminate\Http\Response|null
*/
private function maybeUploadAvatar(User $user, Request $request)
{
try {
if ($request->has('avatar')) {
$this->uploadAvatar($user, $request);
}
} catch (\Exception $e) {
return response([
'message' => 'Error uploading avatar',
'errors' => [
'avatar' => [
$e->getMessage(),
],
],
], 422);
}

return null;
}

/**
* Statuses this user may submit. An administrator-assigned status that is
* not otherwise available stays valid so saving the profile does not
* reject the account's current value.
*
* @return array<string>
*/
private function selfServiceStatuses(User $user): array
{
$statuses = self::SELF_SERVICE_STATUSES;
if ($user->status && !in_array($user->status, $statuses, true)) {
$statuses[] = $user->status;
}

return $statuses;
}

/**
* A replacement the profile picker can no longer load should not fail the
* rest of the save. Clear missing, deleted, system, and non-ACTIVE users.
*/
private function forgetUnassignableDelegation(array $fields): array
Comment thread
mcraeteisha marked this conversation as resolved.
Resolved
{
if (empty($fields['delegation_user_id'])) {
return $fields;
}

$delegate = User::withTrashed()->find($fields['delegation_user_id']);
if (
!$delegate
|| $delegate->trashed()
|| $delegate->is_system
|| $delegate->status !== 'ACTIVE'
) {
$fields['delegation_user_id'] = null;
}

return $fields;
}

/**
* Merge self-service metadata into the persisted server-managed values.
*/
Expand Down
6 changes: 4 additions & 2 deletions ProcessMaker/Http/Controllers/ProfileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,13 @@ function ($result, $item) {
$currentUser->preferences_2fa = $currentUser->getValid2FAPreferences();
$is2FAEnabledForGroup = $currentUser->in2FAGroupOrIndependent();

$addons = $this->getPluginAddons('edit', []);
$addons = $this->getPluginAddons('edit', ['user' => $currentUser]);
$addonsSettings = $this->getPluginAddons('edit.settings', ['user' => $currentUser]);

return view('profile.edit',
compact('currentUser', 'states', 'timezones', 'countries', 'datetimeFormats',
'status', 'enabled2FA', 'global2FAEnabled', 'is2FAEnabledForGroup', 'addons', 'ssoUser'));
'status', 'enabled2FA', 'global2FAEnabled', 'is2FAEnabledForGroup', 'addons',
'addonsSettings', 'ssoUser'));
}

/**
Expand Down
12 changes: 8 additions & 4 deletions ProcessMaker/Models/Process.php
Original file line number Diff line number Diff line change
Expand Up @@ -724,6 +724,7 @@ public function scalateToManagerIfEnabled($user, $activity, $token, $assignmentT
if (app()->bound('workflow.UserManager') && $assignmentProcess) {
$config = json_decode($activity->getProperty('config', '{}'), true);
$escalateToManager = $config['escalateToManager'] ?? false;
$assignee = User::find($user);
if ($escalateToManager) {
$user = WorkflowUserManager::escalateToManager($token, $user);
} else {
Expand All @@ -732,7 +733,10 @@ public function scalateToManagerIfEnabled($user, $activity, $token, $assignmentT
'process_id' => $this->id,
'request_id' => $token->getInstance()->getId(),
]);
$user = $res['assign_to'];
$assignedUserId = $res['assign_to'] ?? null;
$user = $assignee
? $assignee->acceptResolvedAssignee($assignedUserId)
: $assignedUserId;
}
}
}
Expand Down Expand Up @@ -806,9 +810,9 @@ private function getNextUserFromProcessVariable($activity, $token)
$outOfOffice = User::whereIn('id', array_unique($assignedUsers))->where('status', 'OUT_OF_OFFICE')->get();

foreach ($outOfOffice as $user) {
$delegation = $user->delegationUser()->pluck('id')->toArray();
if ($delegation) {
$users[] = $delegation[0];
$delegationId = $user->activeDelegationUserId();
if ($delegationId) {
$users[] = $delegationId;
}
}

Expand Down
Loading
Loading