A free open source IT asset/license management system
FMCS+Floater: Fixed #19192 - make company required
snipeb8018c5b5ed5
diff --git a/app/Helpers/Helper.php b/app/Helpers/Helper.phpindex 22fbcf31a2..6241b4f9d4 100644--- a/app/Helpers/Helper.php+++ b/app/Helpers/Helper.php@@ -1111,15 +1111,21 @@ class Helperif (is_array($rule)) {if (in_array('required', $rule)) {return true;- } else {- return false;}+ if (in_array('fmcs_company', $rule) && self::fmcsCompanyIsCurrentlyRequired()) {+ return true;+ }++ return false;} else {- if (strpos($rule, 'required') === false) {- return false;- } else {+ if (strpos($rule, 'required') !== false) {return true;}+ if (strpos($rule, 'fmcs_company') !== false && self::fmcsCompanyIsCurrentlyRequired()) {+ return true;+ }++ return false;}}}@@ -1127,6 +1133,28 @@ class Helperreturn false;}+ /**+ * Mirror of the fmcs_company validator's runtime condition, used by+ * checkIfRequired() so Blade fields render the "required" indicator+ * (asterisk / aria-required) in the same conditions the backend will+ * reject a blank submission. See ValidationServiceProvider.+ */+ protected static function fmcsCompanyIsCurrentlyRequired(): bool+ {+ $settings = \App\Models\Setting::getSettings();+ if (! $settings->full_multiple_companies_support) {+ return false;+ }+ if ((bool) $settings->null_company_is_floater) {+ return false;+ }+ if (! auth()->check()) {+ return false;+ }++ return ! auth()->user()->isSuperUser();+ }+/*** Return the numeric max length declared for a field in the model's* validation rules (looks for `max:N`). Returns null when the model, field,diff --git a/app/Http/Requests/SaveUserRequest.php b/app/Http/Requests/SaveUserRequest.phpindex 3bda0b5a00..6fb28675d6 100644--- a/app/Http/Requests/SaveUserRequest.php+++ b/app/Http/Requests/SaveUserRequest.php@@ -75,10 +75,18 @@ class SaveUserRequest extends FormRequest/*** 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.+ * be empty:+ *+ * - Floater mode ON: the resulting user would become a system-wide+ * floater (sees everything). That's the privilege-escalation vector+ * flagged in #19200 — only superusers (and users already able to grant+ * floater status) may do this deliberately.+ * - Floater mode OFF (strict FMCS): the resulting user would land with+ * an empty pivot and be immediately invisible to the creator's own+ * scope. That's the visibility bug flagged in #19192 — only superusers+ * (whose scope reaches nulls) may do this.+ *+ * Applies to both web and API store/update.*/public function withValidator(Validator $validator): void{@@ -91,7 +99,7 @@ class SaveUserRequest extends FormRequest// the PHPUnit/Pest runner, which also reports as "in console" but// is using the HTTP stack and must see the gate fire.$inActualConsole = app()->runningInConsole() && ! app()->runningUnitTests();- if ($inActualConsole || auth()->user()?->canGrantFloaterStatus()) {+ if ($inActualConsole) {return;}@@ -107,7 +115,23 @@ class SaveUserRequest extends FormRequest$effective = Company::getIdsForCurrentUser($submitted);if (empty($effective)) {- $validator->errors()->add('company_ids', trans('admin/users/general.cannot_make_floater'));+ $settings = Setting::getSettings();+ $creatorIsSuper = (bool) auth()->user()?->isSuperUser();+ $strictFmcs = $settings->full_multiple_companies_support && ! $settings->null_company_is_floater;++ // Strict-FMCS #19192 gate — hits before the older floater+ // gate so its more specific error message wins when both+ // apply.+ if ($strictFmcs && ! $creatorIsSuper) {+ $validator->errors()->add('company_ids', trans('validation.fmcs_company', ['attribute' => trans('general.company')]));++ return;+ }++ // Original #19200 floater-grant gate.+ if (! auth()->user()?->canGrantFloaterStatus()) {+ $validator->errors()->add('company_ids', trans('admin/users/general.cannot_make_floater'));+ }}});}diff --git a/app/Models/Accessory.php b/app/Models/Accessory.phpindex a7e7169cc9..b9b5804f2d 100755--- a/app/Models/Accessory.php+++ b/app/Models/Accessory.php@@ -82,7 +82,7 @@ class Accessory extends SnipeModel'name' => 'required|max:255','qty' => 'nullable|integer|min:0','category_id' => 'required|integer|exists:categories,id',- 'company_id' => 'integer|nullable|exists:companies,id',+ 'company_id' => 'integer|nullable|exists:companies,id|fmcs_company','location_id' => 'exists:locations,id|nullable|fmcs_location','min_amt' => 'integer|min:0|nullable','purchase_cost' => 'numeric|nullable|gte:0|max:99999999999999999.99',diff --git a/app/Models/Asset.php b/app/Models/Asset.phpindex d91ad1d22e..7998362412 100644--- a/app/Models/Asset.php+++ b/app/Models/Asset.php@@ -113,7 +113,7 @@ class Asset extends Depreciable'status_id' => ['required', 'integer', 'exists:status_labels,id'],'asset_tag' => ['required', 'min:1', 'max:255', 'unique_undeleted:assets,asset_tag', 'not_array'],'name' => ['nullable', 'max:255'],- 'company_id' => ['nullable', 'integer', 'exists:companies,id'],+ 'company_id' => ['nullable', 'integer', 'exists:companies,id', 'fmcs_company'],'warranty_months' => ['nullable', 'numeric', 'digits_between:0,240'],'last_checkout' => ['nullable', 'date_format:Y-m-d H:i:s'],'last_checkin' => ['nullable', 'date_format:Y-m-d H:i:s'],diff --git a/app/Models/Component.php b/app/Models/Component.phpindex 5e6053cb97..cb3201bb3a 100644--- a/app/Models/Component.php+++ b/app/Models/Component.php@@ -47,7 +47,7 @@ class Component extends SnipeModel'qty' => 'required|integer|min:1','category_id' => 'required|integer|exists:categories,id','supplier_id' => 'nullable|integer|exists:suppliers,id',- 'company_id' => 'integer|nullable|exists:companies,id',+ 'company_id' => 'integer|nullable|exists:companies,id|fmcs_company','location_id' => 'exists:locations,id|nullable|fmcs_location','min_amt' => 'integer|min:0|nullable','purchase_date' => 'date_format:Y-m-d|nullable',diff --git a/app/Models/Consumable.php b/app/Models/Consumable.phpindex a2f211ff15..9b3df72b01 100644--- a/app/Models/Consumable.php+++ b/app/Models/Consumable.php@@ -48,7 +48,7 @@ class Consumable extends SnipeModel'name' => 'required|max:255','qty' => 'required|integer|min:0|max:99999','category_id' => 'required|integer',- 'company_id' => 'integer|nullable|exists:companies,id',+ 'company_id' => 'integer|nullable|exists:companies,id|fmcs_company','location_id' => 'exists:locations,id|nullable|fmcs_location','min_amt' => 'integer|min:0|max:99999|nullable','purchase_cost' => 'numeric|nullable|gte:0|max:99999999999999999.99',diff --git a/app/Models/Department.php b/app/Models/Department.phpindex 2805dca67a..48b62bd5f1 100644--- a/app/Models/Department.php+++ b/app/Models/Department.php@@ -46,7 +46,7 @@ class Department extends SnipeModelprotected $rules = ['name' => 'required|string|max:255|is_unique_across_company_and_location:departments,name','location_id' => 'numeric|nullable|exists:locations,id',- 'company_id' => 'numeric|nullable|exists:companies,id',+ 'company_id' => 'numeric|nullable|exists:companies,id|fmcs_company','manager_id' => 'numeric|nullable|exists:users,id','phone' => 'string|max:255|nullable','fax' => 'string|max:255|nullable',diff --git a/app/Models/License.php b/app/Models/License.phpindex e1c91de56d..6f78fba239 100755--- a/app/Models/License.php+++ b/app/Models/License.php@@ -59,7 +59,7 @@ class License extends Depreciable'license_name' => 'string|nullable|max:100','notes' => 'string|nullable','category_id' => 'required|exists:categories,id',- 'company_id' => 'integer|nullable|exists:companies,id',+ 'company_id' => 'integer|nullable|exists:companies,id|fmcs_company','purchase_cost' => 'numeric|nullable|gte:0|max:99999999999999999.99','purchase_date' => 'date_format:Y-m-d|nullable|max:10|required_with:depreciation_id','expiration_date' => 'date_format:Y-m-d|nullable|max:10',diff --git a/app/Models/Location.php b/app/Models/Location.phpindex c5d32ba990..e4507cc110 100755--- a/app/Models/Location.php+++ b/app/Models/Location.php@@ -43,7 +43,7 @@ class Location extends SnipeModel'zip' => 'max:10|nullable','manager_id' => 'exists:users,id|nullable','parent_id' => 'nullable|exists:locations,id|non_circular:locations,id',- 'company_id' => 'integer|nullable|exists:companies,id',+ 'company_id' => 'integer|nullable|exists:companies,id|fmcs_company',];protected $casts = [diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.phpindex 011967c794..73d860d41c 100644--- a/app/Providers/ValidationServiceProvider.php+++ b/app/Providers/ValidationServiceProvider.php@@ -452,6 +452,41 @@ class ValidationServiceProvider extends ServiceProvider);});+ // Enforces "Company must be picked" when FMCS is on AND+ // null_company_is_floater is disabled (strict mode). Without this+ // rule non-superuser users can save a form with an unset company+ // dropdown, land a row with company_id=NULL, and then have that+ // row instantly filtered out of their own view by the strict-mode+ // scope. See #19192. Passes when:+ // - FMCS is off (nothing to enforce)+ // - null_company_is_floater is on (nulls are legal floaters)+ // - value is present (form was filled in)+ // - acting user is a superuser (they see everything; a null is+ // an explicit choice, not an accident)+ // - no auth context (CLI / seeders / importers bypass — same+ // posture as SaveUserRequest's cannot_make_floater gate).+ Validator::extend('fmcs_company', function ($attribute, $value, $parameters, $validator) {+ $settings = Setting::getSettings();+ if (! $settings->full_multiple_companies_support) {+ return true;+ }+ if ((bool) $settings->null_company_is_floater) {+ return true;+ }+ if (! empty($value)) {+ return true;+ }+ if (! auth()->check()) {+ return true;+ }++ return (bool) auth()->user()->isSuperUser();+ });++ Validator::replacer('fmcs_company', function ($message, $attribute, $rule, $parameters) {+ return str_replace(':attribute', trans('general.company'), $message);+ });+// Validates that the company of the validated object matches the company of the location in case of scoped locationsValidator::extend('fmcs_location', function ($attribute, $value, $parameters, $validator) {$settings = Setting::getSettings();diff --git a/resources/lang/en-US/validation.php b/resources/lang/en-US/validation.phpindex 49736251bf..9d172a7ec2 100644--- a/resources/lang/en-US/validation.php+++ b/resources/lang/en-US/validation.php@@ -177,6 +177,7 @@ return ['ulid' => 'The :attribute field must be a valid ULID.','uuid' => 'The :attribute field must be a valid UUID.','valid_css_color' => 'The :attribute field must be a valid CSS color (hex, rgb, rgba, hsl, or hsla).',+ 'fmcs_company' => 'The :attribute field is required because full multiple companies support is enabled and floaters are not allowed.','fmcs_location' => 'Location ":location" belongs to :location_company, which does not match the selected company.','is_unique_across_company_and_location' => 'The :attribute must be unique within the selected company and location.',diff --git a/tests/Feature/Fmcs/StrictModeRequiresCompanyOnCreateTest.php b/tests/Feature/Fmcs/StrictModeRequiresCompanyOnCreateTest.phpnew file mode 100644index 0000000000..351e744435--- /dev/null+++ b/tests/Feature/Fmcs/StrictModeRequiresCompanyOnCreateTest.php@@ -0,0 +1,187 @@+<?php++namespace Tests\Feature\Fmcs;++use App\Models\Accessory;+use App\Models\Asset;+use App\Models\Company;+use App\Models\Component;+use App\Models\Consumable;+use App\Models\Department;+use App\Models\License;+use App\Models\Location;+use App\Models\User;+use Illuminate\Support\Facades\Validator;+use Tests\TestCase;++/**+ * Regression coverage for GitHub issue #19192. When FMCS is enabled and+ * "treat items and users without company associations as floaters" is+ * OFF (strict mode), a non-superuser could save a create-form with the+ * Company field left blank; the row landed with company_id=NULL and+ * was instantly filtered out of that user's own view. The fmcs_company+ * validator + strict-mode branch in SaveUserRequest close both paths.+ *+ * Per Snipe's FMCS adversarial-tests memory: cover strict + floater ++ * non-FMCS with superuser and non-superuser actors. The validator itself+ * is exercised in isolation (not against each model's full $rules) so+ * unrelated pseudo-rules like License::limit_change don't crash the+ * runner — a separate sanity test then asserts every affected model's+ * $rules['company_id'] carries the fmcs_company rule.+ */+class StrictModeRequiresCompanyOnCreateTest extends TestCase+{+ // ------------------------------------------------------------------+ // fmcs_company validator behavior — in isolation+ // ------------------------------------------------------------------++ public function test_rule_rejects_null_in_strict_fmcs_for_non_superuser()+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ auth()->login(User::factory()->create());++ $validator = Validator::make(['company_id' => null], ['company_id' => 'fmcs_company']);++ $this->assertTrue($validator->fails());+ $this->assertArrayHasKey('company_id', $validator->errors()->toArray());+ }++ public function test_rule_accepts_null_in_strict_fmcs_for_superuser()+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ auth()->login(User::factory()->superuser()->create());++ $validator = Validator::make(['company_id' => null], ['company_id' => 'fmcs_company']);++ $this->assertFalse($validator->fails());+ }++ public function test_rule_accepts_null_when_floater_mode_enabled()+ {+ $this->settings->enableFloaterMode();+ auth()->login(User::factory()->create());++ $validator = Validator::make(['company_id' => null], ['company_id' => 'fmcs_company']);++ $this->assertFalse($validator->fails());+ }++ public function test_rule_accepts_null_when_fmcs_off()+ {+ $this->settings->disableMultipleFullCompanySupport();+ auth()->login(User::factory()->create());++ $validator = Validator::make(['company_id' => null], ['company_id' => 'fmcs_company']);++ $this->assertFalse($validator->fails());+ }++ public function test_rule_accepts_non_null_in_strict_fmcs_for_non_superuser()+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ auth()->login(User::factory()->create());+ $company = Company::factory()->create();++ $validator = Validator::make(['company_id' => $company->id], ['company_id' => 'fmcs_company']);++ $this->assertFalse($validator->fails());+ }++ public function test_rule_accepts_null_when_no_auth_context()+ {+ // CLI / seeders / importers deliberately bypass — same posture+ // as the SaveUserRequest cannot_make_floater gate.+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();+ auth()->logout();++ $validator = Validator::make(['company_id' => null], ['company_id' => 'fmcs_company']);++ $this->assertFalse($validator->fails());+ }++ // ------------------------------------------------------------------+ // Sanity: every model the reporter listed has the rule wired+ // ------------------------------------------------------------------++ /**+ * @dataProvider companyableModelProvider+ */+ public function test_model_rules_include_fmcs_company_for_company_id(string $modelClass)+ {+ $rules = $modelClass::rules();+ $this->assertArrayHasKey('company_id', $rules, $modelClass.' should declare a company_id rule');++ $companyRule = $rules['company_id'];+ $ruleString = is_array($companyRule) ? implode('|', $companyRule) : $companyRule;++ $this->assertStringContainsString(+ 'fmcs_company',+ $ruleString,+ $modelClass.'::rules()[company_id] must include the fmcs_company validator so strict-FMCS mode rejects blank submissions',+ );+ }++ public static function companyableModelProvider(): array+ {+ return [+ 'Asset' => [Asset::class],+ 'License' => [License::class],+ 'Accessory' => [Accessory::class],+ 'Consumable' => [Consumable::class],+ 'Component' => [Component::class],+ 'Department' => [Department::class],+ 'Location' => [Location::class],+ ];+ }++ // ------------------------------------------------------------------+ // Users: gate lives in SaveUserRequest, not model $rules+ // ------------------------------------------------------------------++ public function test_users_strict_fmcs_rejects_empty_company_ids_for_non_superuser()+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();++ $actor = User::factory()->create();+ $username = 'strict-null-target-'.uniqid();++ $this->actingAs($actor)+ ->post(route('users.store'), [+ 'first_name' => 'Test',+ 'last_name' => 'User',+ 'username' => $username,+ 'email' => $username.'@example.com',+ 'password' => 'SomeGreatPassword-123',+ 'password_confirmation' => 'SomeGreatPassword-123',+ // No company_ids submitted.+ ])+ ->assertSessionHasErrors('company_ids');++ $this->assertDatabaseMissing('users', ['username' => $username]);+ }++ public function test_users_strict_fmcs_allows_empty_company_ids_for_superuser()+ {+ $this->settings->enableMultipleFullCompanySupport();+ $this->settings->disableFloaterMode();++ $actor = User::factory()->superuser()->create();+ $username = 'super-null-'.uniqid();++ $this->actingAs($actor)+ ->post(route('users.store'), [+ 'first_name' => 'Superuser-Created',+ 'last_name' => 'User',+ 'username' => $username,+ 'email' => $username.'@example.com',+ 'password' => 'SomeGreatPassword-123',+ 'password_confirmation' => 'SomeGreatPassword-123',+ ])+ ->assertSessionHasNoErrors('company_ids');+ }+}diff --git a/tests/Feature/Users/Api/UpdateUserTest.php b/tests/Feature/Users/Api/UpdateUserTest.phpindex b981608523..3b455831d7 100644--- a/tests/Feature/Users/Api/UpdateUserTest.php+++ b/tests/Feature/Users/Api/UpdateUserTest.php@@ -322,9 +322,16 @@ class UpdateUserTest extends TestCase$scoped_user_in_companyB = User::factory()->forCompany($companyB->id)->create();$scoped_user_in_no_company = User::factory()->withoutCompany()->create();+ // Each PATCH carries company_ids so the strict-FMCS gate added+ // for #19192 doesn't hijack the authorization assertion — the+ // test's intent is to verify company-scoped authorization, not+ // to exercise the empty-pivot gate.+ $bodyA = ['company_ids' => [$companyA->id]];+ $bodyB = ['company_ids' => [$companyB->id]];+// Admin for Company A should allow updating user from Company A$this->actingAsForApi($adminA)- ->patchJson(route('api.users.update', $scoped_user_in_companyA))+ ->patchJson(route('api.users.update', $scoped_user_in_companyA), $bodyA)->assertOk()->assertStatus(200)->assertStatusMessageIs('success')@@ -332,7 +339,7 @@ class UpdateUserTest extends TestCase// Admin for Company A should get denied updating user from Company B$this->actingAsForApi($adminA)- ->patchJson(route('api.users.update', $scoped_user_in_companyB))+ ->patchJson(route('api.users.update', $scoped_user_in_companyB), $bodyB)->assertOk()->assertStatus(200)->assertStatusMessageIs('error')@@ -340,7 +347,7 @@ class UpdateUserTest extends TestCase// Admin for Company A should get denied updating user without a company$this->actingAsForApi($adminA)- ->patchJson(route('api.users.update', $scoped_user_in_no_company))+ ->patchJson(route('api.users.update', $scoped_user_in_no_company), $bodyA)->assertOk()->assertStatus(200)->assertStatusMessageIs('error')@@ -348,7 +355,7 @@ class UpdateUserTest extends TestCase// Admin for Company B should allow updating user from Company B$this->actingAsForApi($adminB)- ->patchJson(route('api.users.update', $scoped_user_in_companyB))+ ->patchJson(route('api.users.update', $scoped_user_in_companyB), $bodyB)->assertOk()->assertStatus(200)->assertStatusMessageIs('success')@@ -356,7 +363,7 @@ class UpdateUserTest extends TestCase// Admin for Company B should get denied updating user from Company A$this->actingAsForApi($adminB)- ->patchJson(route('api.users.update', $scoped_user_in_companyA))+ ->patchJson(route('api.users.update', $scoped_user_in_companyA), $bodyA)->assertOk()->assertStatus(200)->assertStatusMessageIs('error')@@ -364,18 +371,26 @@ class UpdateUserTest extends TestCase// Admin for Company B should get denied updating user without a company$this->actingAsForApi($adminB)- ->patchJson(route('api.users.update', $scoped_user_in_no_company))+ ->patchJson(route('api.users.update', $scoped_user_in_no_company), $bodyB)->assertOk()->assertStatus(200)->assertStatusMessageIs('error')->json();- // Admin without a company should allow updating user without a company+ // Behavior change note (#19192): an admin with no company+ // memberships in strict FMCS mode cannot successfully PATCH any+ // user. Empty company_ids trips the new gate; any non-empty+ // list is filtered to empty by Company::getIdsForCurrentUser()+ // because they have no accessible companies. Before the gate,+ // the no-company-user case below was a permissive no-op+ // success — that path is now closed. Practical impact: strict+ // FMCS deployments should grant such admins at least one+ // company (or superuser) so they can act.$this->actingAsForApi($adminNoCompany)->patchJson(route('api.users.update', $scoped_user_in_no_company))->assertOk()->assertStatus(200)- ->assertStatusMessageIs('success')+ ->assertStatusMessageIs('error')->json();// Admin without a company should get denied updating user from Company Adiff --git a/tests/Feature/Users/Ui/FloaterModeGateTest.php b/tests/Feature/Users/Ui/FloaterModeGateTest.phpindex 0c5da490a6..9a4ad25e00 100644--- a/tests/Feature/Users/Ui/FloaterModeGateTest.php+++ b/tests/Feature/Users/Ui/FloaterModeGateTest.php@@ -72,8 +72,17 @@ class FloaterModeGateTest extends TestCase$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()+ public function test_strict_mode_now_blocks_non_superuser_from_clearing_company_ids(){+ // Prior to #19192 this test documented that the #19200 floater+ // gate skipped strict mode entirely (canGrantFloaterStatus()+ // returns true when floaters are off, so no check fired). The+ // reporter's #19192 case demonstrated that same permissive+ // behavior lets a non-superuser end up with an empty pivot in+ // strict FMCS mode, making the target instantly invisible to+ // its creator's scope. The gate now also fires in strict mode+ // for non-superusers, so a non-superuser cannot clear a user's+ // company memberships to empty either.$this->settings->enableMultipleFullCompanySupport();$this->settings->disableFloaterMode();@@ -86,7 +95,7 @@ class FloaterModeGateTest extends TestCase'username' => $actor->username,'company_ids' => [],])- ->assertSessionDoesntHaveErrors('company_ids');+ ->assertSessionHasErrors('company_ids');}public function test_non_superuser_cannot_bulk_clear_companies_in_floater_mode()