A free open source IT asset/license management system
Added stricter gate checks with FMCS and floater mode is on
snipeb78aedeec230
diff --git a/app/Http/Controllers/Users/BulkUsersController.php b/app/Http/Controllers/Users/BulkUsersController.phpindex cb837028c9..825c09d2e7 100644--- a/app/Http/Controllers/Users/BulkUsersController.php+++ b/app/Http/Controllers/Users/BulkUsersController.php@@ -282,6 +282,13 @@ class BulkUsersController extends Controller$this->update_array['company_id'] = $allowedIds[0] ?? null;}+ // Floater-mode self-elevation guard (#19200). See User::canGrantFloaterStatus.+ $wouldClear = $clearCompanies || ($bulkCompanyIds && empty($allowedIds));+ if ($wouldClear && ! auth()->user()->canGrantFloaterStatus()) {+ return redirect()->route('users.index')+ ->with('error', trans('admin/users/general.cannot_make_floater'));+ }+// Save per-user so UserObserver::updating() fires and all field changes are written// to the Activity Report. A mass update() bypasses model observers entirely.foreach ($users as $user) {diff --git a/app/Http/Requests/SaveUserRequest.php b/app/Http/Requests/SaveUserRequest.phpindex b948911c13..275a7550b5 100644--- a/app/Http/Requests/SaveUserRequest.php+++ b/app/Http/Requests/SaveUserRequest.php@@ -2,9 +2,11 @@namespace App\Http\Requests;+use App\Models\Company;use App\Models\Setting;use App\Rules\UserCannotSwitchCompaniesIfItemsAssigned;use Illuminate\Foundation\Http\FormRequest;+use Illuminate\Validation\Validator;class SaveUserRequest extends FormRequest{@@ -70,4 +72,35 @@ class SaveUserRequest extends FormRequestreturn $rules;}++ /**+ * Block non-superusers from saving a user whose resulting company set would+ * be empty *while floater mode is enabled* — that combination promotes the+ * target user to a system-wide floater (sees everything), and is the+ * privilege-escalation vector flagged in #19200. Superusers can still make+ * floaters intentionally. Applies to web and API store/update.+ */+ public function withValidator(Validator $validator): void+ {+ $validator->after(function (Validator $validator) {+ if (! auth()->check() || auth()->user()->canGrantFloaterStatus()) {+ return;+ }++ // Mirror the controller's resolution: prefer company_ids[], fall+ // back to legacy company_id, intval, drop empties.+ $submitted = (array) ($this->input('company_ids') ?? ($this->filled('company_id') ? [$this->input('company_id')] : []));+ $submitted = array_filter(array_map('intval', $submitted));++ // Filter to companies the actor can actually assign (matches the+ // controller's syncCompaniesWithLogging(Company::getIdsForCurrentUser(...))+ // step). If nothing survives the filter, the save would clear the+ // user's pivot.+ $effective = Company::getIdsForCurrentUser($submitted);++ if (empty($effective)) {+ $validator->errors()->add('company_ids', trans('admin/users/general.cannot_make_floater'));+ }+ });+ }}diff --git a/app/Importer/UserImporter.php b/app/Importer/UserImporter.phpindex 0182c400c1..f9d54d2fc2 100644--- a/app/Importer/UserImporter.php+++ b/app/Importer/UserImporter.php@@ -195,6 +195,15 @@ class UserImporter extends ItemImporter$this->log('No matching user, creating one');+ // Floater-mode escalation guard (#19200). See User::canGrantFloaterStatus.+ if (Auth::check() && empty($companyIds) && ! auth()->user()->canGrantFloaterStatus()) {+ $msg = trans('admin/users/general.cannot_make_floater');+ $this->log('Skipping '.$this->item['username'].': '.$msg);+ $this->addErrorToBag(new User, 'company_id', $msg);++ return;+ }+if (! $this->validateFmcsLocation($this->item['location_id'] ?? null, $companyIds)) {$msg = trans('validation.fmcs_location', ['location' => Location::find($this->item['location_id'])?->name ?? $this->item['location_id'],diff --git a/app/Models/Company.php b/app/Models/Company.phpindex fe8500943d..b8902bc7d4 100644--- a/app/Models/Company.php+++ b/app/Models/Company.php@@ -219,6 +219,18 @@ final class Company extends SnipeModelreturn true;}+ // For User targets the visibility rule is already encoded in the+ // CompanyableScope. If the actor can see this user in their scoped+ // list, they can act on it (the role-permission check that runs+ // after this still has final say). Doing this here keeps per-target+ // access in lockstep with list visibility — the back-patch for+ // #19187 tightened the bypass branch below but never updated the+ // per-target path, which left actors able to see users they+ // couldn't then edit. One check, one query, same logic as the list.+ if ($companyable instanceof User) {+ return User::where('users.id', $companyable->id)->exists();+ }+$userCompanyIds = self::getCurrentUserCompanyIds();// Empty pivot = unrestricted only for true legacy "no-company" users@@ -229,21 +241,6 @@ final class Company extends SnipeModelreturn true;}- // Users are scoped by pivot membership, not company_id, so check the pivot directly.- if ($companyable instanceof User) {- $companyableCompanyIds = DB::table('company_user')- ->where('user_id', $companyable->id)- ->pluck('company_id')- ->toArray();-- // A null-company user (no pivot rows) is accessible in floater mode.- if (empty($companyableCompanyIds)) {- return (bool) Setting::getSettings()->null_company_is_floater;- }-- return ! empty(array_intersect($userCompanyIds, $companyableCompanyIds));- }-$companyable_company_id = ($companyable instanceof Company)? $companyable->id: $companyable->company_id;diff --git a/app/Models/User.php b/app/Models/User.phpindex 3f3f357fe2..b3466b0000 100644--- a/app/Models/User.php+++ b/app/Models/User.php@@ -566,6 +566,28 @@ class User extends SnipeModel implements AuthenticatableContract, AuthorizableCoreturn $this->checkPermissionSection('admin');}+ /**+ * Whether this user is allowed to save another user with no company+ * assignment. Under floater mode, "no companies" means the target gains+ * system-wide visibility — only superusers are trusted to do that.+ * When floater mode is off, anyone with `users.edit` can clear the pivot+ * (no escalation possible, the target just becomes unscoped). When FMCS+ * itself is off the whole notion is moot. See #19200.+ */+ public function canGrantFloaterStatus(): bool+ {+ $settings = Setting::getSettings();++ if (! $settings->full_multiple_companies_support) {+ return true;+ }+ if (! $settings->null_company_is_floater) {+ return true;+ }++ return $this->isSuperUser();+ }+/*** Checks if the user can edit their own profile*diff --git a/resources/lang/en-US/admin/users/general.php b/resources/lang/en-US/admin/users/general.phpindex b73f0efd7f..c63d61af28 100644--- a/resources/lang/en-US/admin/users/general.php+++ b/resources/lang/en-US/admin/users/general.php@@ -60,4 +60,9 @@ return ['department_manager' => 'Department Manager','generate_password' => 'Generate random password','individual_override' => 'This user has at least one individual permission set, which may override group permissions.',+ 'cannot_make_floater' => 'Cannot save this user with no company assignment. Floater mode is enabled on this system, which means users with no company can see every record in the application. Only superusers can grant a user floater status.',+ 'floater_mode_warning_help' => 'Floater mode is enabled. A user with no company assignment will be able to see every record in the system. Only superusers can save a user with no company.',+ 'no_companies_assigned' => '(No companies assigned)',+ 'cannot_edit_privileged_user_companies' => 'Only an admin or super admin can modify the company assignments of an admin or super admin user.',+ 'cannot_manage_companies_without_membership' => 'Full multiple company support with floater mode is enabled, so you must be assigned to at least one company before you can manage another user\'s company assignments.',];diff --git a/resources/views/users/edit.blade.php b/resources/views/users/edit.blade.phpindex a0875ac463..b47e0a85d2 100755--- a/resources/views/users/edit.blade.php+++ b/resources/views/users/edit.blade.php@@ -344,27 +344,47 @@<!-- Company -->+ {{-- selected reads from the company_user pivot only; the legacy users.company_id+ scalar can lag behind (LDAP sync, pre-observer rows, etc.) so we never fall+ back to it or the dropdown would show ghost selections. --}}@if ((Gate::allows('canEditAuthFields', $user)) && (\App\Models\Company::canManageUsersCompanies()))@include ('partials.forms.edit.company-select', ['translated_name' => trans('general.company'),'fieldname' => 'company_ids','multiple' => 'true',- 'selected' => old('company_ids', $user->companies->isNotEmpty() ? $user->companies->pluck('id')->toArray() : ($user->company_id ? [$user->company_id] : [])),+ 'selected' => old('company_ids', $user->companies->pluck('id')->toArray()),])+ @if (! auth()->user()->canGrantFloaterStatus())+ <div class="col-md-6 col-md-offset-3">+ <p class="help-block"><x-icon type="warning" /> {{ trans('admin/users/general.floater_mode_warning_help') }}</p>+ </div>+ @endif@else- @if ($user->companies->isNotEmpty())- <div class="form-group">- <label class="col-md-3 control-label" for="locale">{{ trans('general.company') }}</label>- <div class="col-md-6">- <p class="form-control-static">+ {{-- Field stays visible even when read-only so it's clear it exists and+ what it would have shown. Body is the target's current companies if any,+ or a "(no companies)" note, plus a help line explaining why it's locked. --}}+ <div class="form-group">+ <label class="col-md-3 control-label">{{ trans('general.company') }}</label>+ <div class="col-md-6">+ <p class="form-control-static">+ @if ($user->companies->isNotEmpty())@foreach ($user->companies as $company)<span class="label label-light">{!! $company->present()->formattedNameLink !!}</span>@endforeach-- </p>- </div>+ @else+ <em class="text-muted">{{ trans('admin/users/general.no_companies_assigned') }}</em>+ @endif+ </p>+ <p class="help-block">+ <x-icon type="info" />+ @if (! Gate::allows('canEditAuthFields', $user))+ {{ trans('admin/users/general.cannot_edit_privileged_user_companies') }}+ @else+ {{ trans('admin/users/general.cannot_manage_companies_without_membership') }}+ @endif+ </p></div>- @endif+ </div>@endifdiff --git a/tests/Feature/Importing/Api/ImportUsersMultiCompanyTest.php b/tests/Feature/Importing/Api/ImportUsersMultiCompanyTest.phpindex 7b8157ca5b..64abf7bca6 100644--- a/tests/Feature/Importing/Api/ImportUsersMultiCompanyTest.php+++ b/tests/Feature/Importing/Api/ImportUsersMultiCompanyTest.php@@ -108,4 +108,30 @@ class ImportUsersMultiCompanyTest extends ImportDataTestCase$this->assertCount(0, $user->companies, 'Blank company column should leave user with no companies');}++ public function test_non_superuser_cannot_create_floater_user_via_import()+ {+ // #19200: non-superuser importing a new user with no resolvable+ // company while floater mode is on would have minted a floater+ // account — exploitable via the welcome-email + activated columns+ // to hand the attacker valid credentials. Importer must skip the row+ // and leave no user behind.+ $this->settings->enableFloaterMode();++ $importerCompany = Company::factory()->create();+ $importer = $importerCompany->users()->save(+ User::factory()->editUsers()->createUsers()->canImport()->create(),+ );++ $importFileBuilder = ImportFileBuilder::new(['companyName' => '']);+ $row = $importFileBuilder->firstRow();+ $import = Import::factory()->users()->create(['file_path' => $importFileBuilder->saveToImportsDirectory()]);++ $this->actingAsForApi($importer)+ ->importFileResponse(['import' => $import->id]);++ $this->assertDatabaseMissing('users', [+ 'username' => $row['username'],+ ]);+ }}diff --git a/tests/Feature/Users/Ui/FloaterModeGateTest.php b/tests/Feature/Users/Ui/FloaterModeGateTest.phpnew file mode 100644index 0000000000..6db829752d--- /dev/null+++ b/tests/Feature/Users/Ui/FloaterModeGateTest.php@@ -0,0 +1,157 @@+<?php++namespace Tests\Feature\Users\Ui;++use App\Models\Company;+use App\Models\User;+use Tests\TestCase;++/**+ * #19200: with floater mode on, a non-superuser with users.edit could blank a+ * user's company assignments and promote that user (often themselves) to a+ * system-wide floater. SaveUserRequest::withValidator and BulkUsersController+ * both refuse the operation; only superusers can intentionally make a floater.+ */+class FloaterModeGateTest extends TestCase+{+ public function test_non_superuser_cannot_blank_their_own_companies_in_floater_mode()+ {+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $actor = $company->users()->save(User::factory()->editUsers()->create());++ $this->actingAs($actor)+ ->put(route('users.update', $actor), [+ 'first_name' => $actor->first_name,+ 'username' => $actor->username,+ 'company_ids' => [],+ ])+ ->assertSessionHasErrors('company_ids');++ $this->assertContains($company->id, $actor->fresh()->companies->pluck('id')->all(), 'Actor should still belong to original company');+ $this->assertNotEmpty($actor->fresh()->companies, 'Actor pivot should not be wiped');+ }++ public function test_non_superuser_cannot_blank_another_users_companies_in_floater_mode()+ {+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $actor = $company->users()->save(User::factory()->editUsers()->create());+ $victim = $company->users()->save(User::factory()->create());++ $this->actingAs($actor)+ ->put(route('users.update', $victim), [+ 'first_name' => $victim->first_name,+ 'username' => $victim->username,+ 'company_ids' => [],+ ])+ ->assertSessionHasErrors('company_ids');++ $this->assertContains($company->id, $victim->fresh()->companies->pluck('id')->all());+ $this->assertNotEmpty($victim->fresh()->companies, 'Victim pivot should not be wiped');+ }++ public function test_superuser_can_save_a_user_with_no_companies_in_floater_mode()+ {+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $superuser = User::factory()->superuser()->create();+ $target = $company->users()->save(User::factory()->create());++ $this->actingAs($superuser)+ ->put(route('users.update', $target), [+ 'first_name' => $target->first_name,+ 'username' => $target->username,+ 'company_ids' => [],+ ])+ ->assertSessionDoesntHaveErrors('company_ids');++ $this->assertEmpty($target->fresh()->companies->pluck('id')->all(), 'Superuser is trusted to grant floater status');+ }++ public function test_guard_does_not_apply_when_floater_mode_is_off()+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();++ $company = Company::factory()->create();+ $actor = $company->users()->save(User::factory()->editUsers()->create());++ $this->actingAs($actor)+ ->put(route('users.update', $actor), [+ 'first_name' => $actor->first_name,+ 'username' => $actor->username,+ 'company_ids' => [],+ ])+ ->assertSessionDoesntHaveErrors('company_ids');+ }++ public function test_non_superuser_cannot_bulk_clear_companies_in_floater_mode()+ {+ $this->settings->enableFloaterMode();++ $company = Company::factory()->create();+ $actor = $company->users()->save(User::factory()->editUsers()->create());+ $victim = $company->users()->save(User::factory()->create());++ $this->actingAs($actor)+ ->post(route('users/bulkeditsave'), [+ 'ids' => [$victim->id => '1'],+ 'null_company_ids' => '1',+ ])+ ->assertRedirect()+ ->assertSessionHas('error');++ $this->assertContains($company->id, $victim->fresh()->companies->pluck('id')->all(), 'Bulk clear should be refused');+ $this->assertNotEmpty($victim->fresh()->companies);+ }++ public function test_uncompanied_non_superuser_cannot_save_user_with_no_companies()+ {+ // Per spec: under floater mode, ONLY superusers may grant floater+ // status. An uncompanied non-superuser (themselves a floater) was+ // previously trusted to manage other floaters — that's now closed off+ // because it lets the chain "clear pivot → reset target's password+ // (via canEditAuthFields gaps) → log in as a new floater" complete.+ $this->settings->enableFloaterMode();++ $actor = User::factory()->editUsers()->create();+ $actor->companies()->sync([]);+ $target = User::factory()->create();+ $target->companies()->sync([]);++ $this->actingAs($actor)+ ->put(route('users.update', $target), [+ 'first_name' => $target->first_name,+ 'username' => $target->username,+ 'company_ids' => [],+ ])+ ->assertSessionHasErrors('company_ids');+ }++ public function test_non_superuser_can_change_their_companies_to_a_non_empty_set_in_floater_mode()+ {+ $this->settings->enableFloaterMode();++ $companyA = Company::factory()->create();+ $companyB = Company::factory()->create();+ $actor = User::factory()->editUsers()->create();+ $actor->companies()->sync([$companyA->id, $companyB->id]);++ // Drop B, keep A — still has memberships, so not becoming a floater.+ $this->actingAs($actor)+ ->put(route('users.update', $actor), [+ 'first_name' => $actor->first_name,+ 'username' => $actor->username,+ 'company_ids' => [$companyA->id],+ ])+ ->assertSessionDoesntHaveErrors('company_ids');++ $freshIds = $actor->fresh()->companies->pluck('id')->all();+ $this->assertContains($companyA->id, $freshIds);+ $this->assertNotContains($companyB->id, $freshIds);+ }+}diff --git a/tests/Feature/Users/Ui/UpdateUserTest.php b/tests/Feature/Users/Ui/UpdateUserTest.phpindex 471df3e3be..17c011fdd7 100644--- a/tests/Feature/Users/Ui/UpdateUserTest.php+++ b/tests/Feature/Users/Ui/UpdateUserTest.php@@ -25,6 +25,24 @@ class UpdateUserTest extends TestCase->assertOk();}+ public function test_uncompanied_user_can_edit_their_own_record_with_fmcs_on_and_floater_off()+ {+ // Regression: with FMCS on + floater off, the CompanyableScope lets an+ // uncompanied non-superuser see themselves in the users list, but the+ // policy used to 403 the edit because the bypass required the legacy+ // scalar users.company_id column to also be null. Actors are always+ // allowed to access their own record.+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();++ $self = User::factory()->editUsers()->create(['company_id' => null]);+ $self->companies()->sync([]);++ $this->actingAs($self)+ ->get(route('users.edit', $self))+ ->assertOk();+ }+public function test_can_view_edit_page_for_soft_deleted_user(){$user = User::factory()->trashed()->create();