A free open source IT asset/license management system
Added parent_within_scope validator
snipe15fe929f05a6
diff --git a/app/Models/Company.php b/app/Models/Company.phpindex dce4e75610..e9738e1deb 100644--- a/app/Models/Company.php+++ b/app/Models/Company.php@@ -43,7 +43,7 @@ final class Company extends SnipeModel'fax' => 'min:7|max:35|nullable','phone' => 'min:7|max:35|nullable','email' => 'email|max:150|nullable',- 'parent_id' => 'nullable|integer|exists:companies,id|parent_must_be_top_level:companies,id|must_have_no_children:companies,id',+ 'parent_id' => 'nullable|integer|exists:companies,id|parent_must_be_top_level:companies,id|must_have_no_children:companies,id|parent_within_scope',];protected $casts = [diff --git a/app/Providers/ValidationServiceProvider.php b/app/Providers/ValidationServiceProvider.phpindex 713bef68cb..4a5a3d58d2 100644--- a/app/Providers/ValidationServiceProvider.php+++ b/app/Providers/ValidationServiceProvider.php@@ -2,6 +2,7 @@namespace App\Providers;+use App\Models\Company;use App\Models\CustomField;use App\Models\Location;use App\Models\Setting;@@ -323,6 +324,42 @@ class ValidationServiceProvider extends ServiceProviderreturn ! DB::table($table)->where('parent_id', $modelId)->exists();});+ // Companion to `parent_must_be_top_level` / `must_have_no_children`:+ // enforce that the caller is authorized to re-parent the row under the+ // chosen new parent. Without this check, a scoped non-superuser+ // holding companies.edit could PATCH their own company's parent_id to+ // a foreign top-level company id — the structural rules above accept+ // it because they only look at the parent's shape (top-level, no+ // children), not the caller's scope. Company::getCurrentUserCompanyIds+ // then walks parent+children so re-parenting A under B silently+ // expands every B member's scope to include A. Bypasses CompanyableScope+ // on the lookup for the same reason `fmcs_location` does: the scope+ // hides foreign rows and would fall through to "not found" here.+ Validator::extend('parent_within_scope', function ($attribute, $value, $parameters, $validator) {+ if ($value === null || $value === '' || (int) $value === 0) {+ return true;+ }++ // CLI / system context (seeders, artisan) has no auth user to scope+ // against. Skip the check so trusted callers still work.+ if (! auth()->user()) {+ return true;+ }++ // Deliberately not going through Company::isCurrentUserHasAccess.+ // That helper short-circuits `return true` for any Companyable+ // whose table has no `company_id` column, which includes the+ // companies table itself (the tenant boundary). Directly filtering+ // the requested id against the actor's expanded company set+ // matches what CompanyableScope enforces on reads and applies the+ // superuser / non-FMCS bypasses via getIdsForCurrentUser.+ return ! empty(Company::getIdsForCurrentUser([(int) $value]));+ });++ Validator::replacer('parent_within_scope', function ($message) {+ return str_replace(':attribute', trans('general.company'), $message);+ });+// Yo dawg. I heard you like validators.// This validates the custom validator regex in custom fields.// We're just checking that the regex won't throw an exception, notdiff --git a/resources/lang/en-US/validation.php b/resources/lang/en-US/validation.phpindex 9d172a7ec2..6ae5c9897c 100644--- a/resources/lang/en-US/validation.php+++ b/resources/lang/en-US/validation.php@@ -162,6 +162,7 @@ return ['non_circular' => 'The :attribute must not create a circular reference.','parent_must_be_top_level' => 'The selected :attribute must itself be a top-level item. Only one level of nesting is allowed.','must_have_no_children' => 'This item already has children of its own, so it cannot be assigned a parent.',+ 'parent_within_scope' => 'The selected :attribute is outside your assigned scope.','not_array' => ':attribute cannot be an array.','disallow_same_pwd_as_user_fields' => 'Password cannot be the same as the username.','letters' => 'Password must contain at least one letter.',diff --git a/tests/Feature/Companies/Api/CompanyHierarchyTest.php b/tests/Feature/Companies/Api/CompanyHierarchyTest.phpindex 703709af34..6615aac16d 100644--- a/tests/Feature/Companies/Api/CompanyHierarchyTest.php+++ b/tests/Feature/Companies/Api/CompanyHierarchyTest.php@@ -611,4 +611,133 @@ class CompanyHierarchyTest extends TestCase$this->assertContains($assetInChild->id, $foundIds, 'Child asset should be visible via hierarchy');$this->assertContains($floaterAsset->id, $foundIds, 'Floater asset should be visible via null_company_is_floater');}++ public function test_scoped_actor_cannot_reparent_own_company_under_a_foreign_top_level_company(): void+ {+ // Under FMCS, Company::getCurrentUserCompanyIds() walks parent++ // children. Re-parenting Company A under Company B would silently+ // expose every Company A resource to every Company B member. The+ // structural parent_must_be_top_level + must_have_no_children+ // rules accept the write because they only look at the parent's+ // shape, not the caller's scope on it. The parent_within_scope+ // rule closes that gap.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $actor = $companyA->users()->save(User::factory()->editCompanies()->make());++ $response = $this->actingAsForApi($actor)+ ->patchJson(route('api.companies.update', ['company' => $companyA->id]), [+ 'name' => $companyA->name,+ 'parent_id' => $companyB->id,+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('error')+ ->assertJsonStructure(['messages' => ['parent_id']]);++ $this->assertNull(+ $companyA->fresh()->parent_id,+ 'Company A must not be re-parented under a company outside the actor\'s scope.',+ );++ $message = implode(' ', (array) $response->json('messages.parent_id'));+ $this->assertStringContainsString('outside your assigned scope', $message);+ }++ public function test_scoped_actor_cannot_create_child_of_foreign_company(): void+ {+ // Sibling of the update case for the create path. Same scope+ // gap, same rule.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $actor = $companyA->users()->save(User::factory()->createCompanies()->make());++ $this->actingAsForApi($actor)+ ->postJson(route('api.companies.store'), [+ 'name' => 'Attempted-Child-Of-B',+ 'parent_id' => $companyB->id,+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('error')+ ->assertJsonStructure(['messages' => ['parent_id']]);++ $this->assertDatabaseMissing('companies', ['name' => 'Attempted-Child-Of-B']);+ }++ public function test_scoped_actor_can_reparent_within_their_own_scope(): void+ {+ // Happy path: user in Company A can re-parent one of their own+ // companies (an orphan they also belong to) under another of+ // their companies. Guards against a fix that would reject every+ // reparent from a non-superuser.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $actor = User::factory()->editCompanies()->create();+ $actor->companies()->sync([$companyA->id, $companyB->id]);++ $orphan = $companyA;+ $newParent = $companyB;++ $this->actingAsForApi($actor)+ ->patchJson(route('api.companies.update', ['company' => $orphan->id]), [+ 'name' => $orphan->name,+ 'parent_id' => $newParent->id,+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('success');++ $this->assertSame($newParent->id, $orphan->fresh()->parent_id);+ }++ public function test_superuser_can_reparent_across_any_companies_under_fmcs(): void+ {+ // Regression guard for the fix. Superusers bypass FMCS scope+ // entirely, so they must still be able to re-parent any company+ // under any other, matching pre-fix behavior.+ $this->settings->enableMultipleFullCompanySupport();++ [$companyA, $companyB] = Company::factory()->count(2)->create();++ $this->actingAsForApi(User::factory()->superuser()->create())+ ->patchJson(route('api.companies.update', ['company' => $companyA->id]), [+ 'name' => $companyA->name,+ 'parent_id' => $companyB->id,+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('success');++ $this->assertSame($companyB->id, $companyA->fresh()->parent_id);+ }++ public function test_scoped_actor_can_clear_parent_id_on_their_own_company(): void+ {+ // Sending parent_id = null (or 0, per the model mutator) never+ // exposes new scope so it must pass regardless of what the+ // parent used to be. Guards against a fix that would insist on+ // scope on the CURRENT parent instead of the NEW one.+ $this->settings->enableMultipleFullCompanySupport();++ $companyA = Company::factory()->create();+ $companyB = Company::factory()->create();++ $child = Company::factory()->create(['parent_id' => $companyB->id]);++ $actor = $companyA->users()->save(User::factory()->editCompanies()->make());+ $actor->companies()->attach($child->id);++ $this->actingAsForApi($actor)+ ->patchJson(route('api.companies.update', ['company' => $child->id]), [+ 'name' => $child->name,+ 'parent_id' => null,+ ])+ ->assertStatus(200)+ ->assertStatusMessageIs('success');++ $this->assertNull($child->fresh()->parent_id);+ }}