A free open source IT asset/license management system
Fixed FD-56789 - tighten user API company controls
snipe836f37f854bc
diff --git a/app/Http/Controllers/Api/UsersController.php b/app/Http/Controllers/Api/UsersController.phpindex 2bb58b9a32..915cb54c49 100644--- a/app/Http/Controllers/Api/UsersController.php+++ b/app/Http/Controllers/Api/UsersController.php@@ -30,6 +30,7 @@ use Illuminate\Database\Eloquent\Builder;use Illuminate\Http\JsonResponse;use Illuminate\Http\Request;use Illuminate\Support\Facades\Artisan;+use Illuminate\Support\Facades\DB;use Illuminate\Support\Facades\Log;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Facades\Validator;@@ -480,6 +481,45 @@ class UsersController extends Controller$this->authorize('create', User::class);$authenticatedUser = auth()->user();++ // Resolve requested company memberships up front, BEFORE any user+ // record or pivot row lands on the DB. Prior behavior filled and+ // saved the user first, then filtered company IDs after the fact+ // (see syncCompaniesWithLogging below). A non-superuser could+ // submit a company_id belonging to another company they were not+ // a member of; the user row was persisted before the filter ran,+ // producing an unauthorized cross-tenant record even when the+ // pivot ended up empty (leaving the account as a floater under+ // null_company_is_floater installs). Reject the whole request if+ // any requested id fails the actor's permitted-companies filter.+ $requestedCompanyIds = array_values(array_filter(array_map(+ 'intval',+ (array) ($request->input('company_ids') ?? ($request->filled('company_id') ? [$request->input('company_id')] : [])),+ )));+ $permittedCompanyIds = Company::getIdsForCurrentUser($requestedCompanyIds);++ if (count($requestedCompanyIds) !== count($permittedCompanyIds)) {+ return response()->json(Helper::formatStandardApiResponse(+ 'error',+ null,+ trans('admin/users/message.error.company_not_permitted'),+ ), 403);+ }++ // Groups validation runs BEFORE save so the transaction below is a+ // straight-line succeed-or-rollback. Doing it after save (as the+ // pre-refactor version did) meant a bad groups payload persisted a+ // user record even though the response reported "error".+ if (($request->has('groups')) && (auth()->user()->isSuperUser())) {+ $groupsValidator = Validator::make($request->only('groups'), [+ 'groups.*' => 'integer|exists:permission_groups,id',+ ]);++ if ($groupsValidator->fails()) {+ return response()->json(Helper::formatStandardApiResponse('error', null, $groupsValidator->errors()));+ }+ }+$user = new User;$user->fill($request->all());$user->created_by = auth()->id();@@ -491,7 +531,6 @@ class UsersController extends Controller));}- //if ($request->filled('password')) {$user->password = bcrypt($request->input('password'));} else {@@ -500,7 +539,19 @@ class UsersController extends Controllerapp('App\Http\Requests\ImageUploadRequest')->handleImages($user, 600, 'avatar', 'avatars', 'avatar');- if ($user->save()) {+ // Wrap save + groups + company sync in a single transaction so a+ // failure anywhere in the create sequence rolls back the whole+ // thing. Without this, an exception in syncCompaniesWithLogging()+ // or groups()->sync() would leave a partially-created user record+ // on the DB with unfiltered attribute state from $request->all().+ $saveFailed = false;++ DB::transaction(function () use ($request, $user, $permittedCompanyIds, &$saveFailed) {+ if (! $user->save()) {+ $saveFailed = true;++ return;+ }if (($user->activated == '1') && ($user->email != '') && ($request->input('send_welcome') == '1')) {@@ -513,29 +564,17 @@ class UsersController extends Controller}if (($request->has('groups')) && (auth()->user()->isSuperUser())) {-- $validator = Validator::make($request->only('groups'), [- 'groups.*' => 'integer|exists:permission_groups,id',- ]);-- if ($validator->fails()) {- return response()->json(Helper::formatStandardApiResponse('error', null, $validator->errors()));- }-- // Sync the groups since the user is a superuser and the groups pass validation$user->groups()->sync($request->input('groups'));}- // Sync company memberships from company_ids[] or fall back to scalar company_id- $companyIds = array_filter(- (array) ($request->input('company_ids') ?? ($request->filled('company_id') ? [$request->input('company_id')] : []))- );- $user->syncCompaniesWithLogging(Company::getIdsForCurrentUser(array_map('intval', $companyIds)));+ $user->syncCompaniesWithLogging($permittedCompanyIds);+ });- return response()->json(Helper::formatStandardApiResponse('success', (new UsersTransformer)->transformUser($user), trans('admin/users/message.success.create')));+ if ($saveFailed) {+ return response()->json(Helper::formatStandardApiResponse('error', null, $user->getErrors()));}- return response()->json(Helper::formatStandardApiResponse('error', null, $user->getErrors()));+ return response()->json(Helper::formatStandardApiResponse('success', (new UsersTransformer)->transformUser($user), trans('admin/users/message.success.create')));}/**@@ -584,6 +623,30 @@ class UsersController extends Controllerreturn response()->json(Helper::formatStandardApiResponse('error', null, 'Permission denied. You cannot update user information via API on the demo.'));}+ // Resolve requested company memberships up front, BEFORE any DB+ // write. Same reasoning as store(): the pre-refactor update path+ // filled the user record from $request->all() and saved it, then+ // filtered the company IDs afterward. A non-superuser could+ // therefore relocate an existing user into a different company+ // via a scalar company_id or company_ids[] payload. Reject the+ // whole request if any requested id fails the actor's permitted+ // companies filter.+ if ($request->has('company_ids') || $request->filled('company_id')) {+ $requestedCompanyIds = array_values(array_filter(array_map(+ 'intval',+ (array) ($request->input('company_ids') ?? [$request->input('company_id')]),+ )));+ $permittedCompanyIds = Company::getIdsForCurrentUser($requestedCompanyIds);++ if (count($requestedCompanyIds) !== count($permittedCompanyIds)) {+ return response()->json(Helper::formatStandardApiResponse(+ 'error',+ null,+ trans('admin/users/message.error.company_not_permitted'),+ ), 403);+ }+ }+// User::GATED_AUTH_FIELDS enter through the canEditAuthFields branch// below. If the caller does not hold that gate against this target// but their request nevertheless carries any of those fields, faildiff --git a/resources/lang/en-US/admin/users/message.php b/resources/lang/en-US/admin/users/message.phpindex 533e5114f4..d20c990e50 100644--- a/resources/lang/en-US/admin/users/message.php+++ b/resources/lang/en-US/admin/users/message.php@@ -68,6 +68,7 @@ return ['password_ldap' => 'The password for this account is managed by LDAP/Active Directory. Please contact your IT department to change your password. ','multi_company_items_assigned' => 'This user has items assigned that belong to a different company. Please check them in or edit their company.','no_pending_acceptances' => 'This user has no pending acceptances to remind them about.',+ 'company_not_permitted' => 'One or more requested company assignments are outside your permitted company scope.',],'deletefile' => [diff --git a/tests/Feature/Users/Api/UserCompanyMembershipTest.php b/tests/Feature/Users/Api/UserCompanyMembershipTest.phpindex c4f3058fe5..708ebec731 100644--- a/tests/Feature/Users/Api/UserCompanyMembershipTest.php+++ b/tests/Feature/Users/Api/UserCompanyMembershipTest.php@@ -279,4 +279,114 @@ class UserCompanyMembershipTest extends TestCase$this->assertNull(User::where('username', 'testuser_invalid_companies')->first());}++ public function test_store_denies_mixed_cross_tenant_company_ids_from_non_superuser()+ {+ // Regression for Christopher Finks / Issue 2. A non-superuser with+ // users.create who is a member of Company A only cannot create a+ // user whose company_ids[] includes any company outside the actor's+ // permitted scope. This exercises the mixed case (some permitted,+ // some not) where SaveUserRequest::withValidator() does not fire+ // its "cannot make floater" gate because the filter still returns+ // a non-empty set. Prior behavior filled and saved the user, then+ // silently dropped the foreign company id at sync time - leaving+ // a user record whose eventual pivot did not match the request.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $actor = User::factory()->createUsers()->forCompany($companyA->id)->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.users.store'), [+ 'first_name' => 'Cross',+ 'last_name' => 'Tenant',+ 'username' => 'cross_tenant_mixed',+ 'password' => 'secret123456',+ 'password_confirmation' => 'secret123456',+ 'company_ids' => [$companyA->id, $companyB->id],+ ])+ ->assertStatus(403);++ $this->assertNull(User::where('username', 'cross_tenant_mixed')->first(), 'User must not be persisted when any requested company is outside the actor scope.');+ }++ public function test_update_denies_mixed_cross_tenant_company_ids_from_non_superuser()+ {+ // Same regression as above but on the update path. Actor edits an+ // existing user's company_ids to include a foreign company alongside+ // their own permitted one - must be rejected before any pivot write.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $target = User::factory()->forCompany($companyA->id)->create();+ $target->companies()->sync([$companyA->id]);+ $actor = User::factory()->editUsers()->forCompany($companyA->id)->create();++ $this->actingAsForApi($actor)+ ->patchJson(route('api.users.update', $target), [+ 'first_name' => $target->first_name,+ 'last_name' => $target->last_name,+ 'username' => $target->username,+ 'company_ids' => [$companyA->id, $companyB->id],+ ])+ ->assertStatus(403);++ $target->refresh();+ $this->assertFalse($target->companies->contains($companyB), 'Cross-tenant company must not be attached on update.');+ $this->assertTrue($target->companies->contains($companyA), 'Existing legitimate company assignment must survive the rejection.');+ }++ public function test_store_scalar_cross_tenant_company_id_rejected_by_validation()+ {+ // Scalar company_id case with a single foreign company id is+ // rejected earlier by SaveUserRequest::withValidator() (the+ // "cannot make floater" gate fires because the permitted-id filter+ // returns empty). Kept here as a coverage marker so this path does+ // not regress and someone does not later remove the validator gate+ // thinking the controller alone protects the endpoint.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();+ $actor = User::factory()->createUsers()->forCompany($companyA->id)->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.users.store'), [+ 'first_name' => 'Cross',+ 'last_name' => 'Tenant',+ 'username' => 'cross_tenant_scalar',+ 'password' => 'secret123456',+ 'password_confirmation' => 'secret123456',+ 'company_id' => $companyB->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('error');++ $this->assertNull(User::where('username', 'cross_tenant_scalar')->first());+ }++ public function test_store_allows_non_superuser_to_assign_own_company()+ {+ // Sanity: the fix should not break the legitimate case of a+ // non-superuser creating a user in their own company.+ $this->settings->enableMultipleFullCompanySupport();++ $company = Company::factory()->create();+ $actor = User::factory()->createUsers()->forCompany($company->id)->create();++ $this->actingAsForApi($actor)+ ->postJson(route('api.users.store'), [+ 'first_name' => 'Same',+ 'last_name' => 'Tenant',+ 'username' => 'same_tenant_ok',+ 'password' => 'secret123456',+ 'password_confirmation' => 'secret123456',+ 'company_id' => $company->id,+ ])+ ->assertOk()+ ->assertStatusMessageIs('success');++ $user = User::where('username', 'same_tenant_ok')->first();+ $this->assertNotNull($user);+ $this->assertTrue($user->companies->contains($company));+ }}